<?php
// +----------------------------------------------------------------------
// | Forpastime
// +----------------------------------------------------------------------
// | Author: Forpastime <Forpastime@qq.com>
// +----------------------------------------------------------------------
namespace plugins\aliyunvod\controller; 
use cmf\controller\PluginRestBaseController;
use think\Db;
use think\facade\Request;
use vod\Request\V20170321 as vod;
use core\DefaultAcsClient;
use core\Profile\DefaultProfile;

class ApiVideoController extends PluginRestBaseController
{
    /**
     * 上传成功后的异步通知
     */
    public function notify()
    {
        $obj= file_get_contents("php://input"); 
        

		$result = json_decode($obj, true); 
		$VideoId=$result["VideoId"];
        $EventType=$result["EventType"];

        
        if($result['Status']=='success'){
        $this->relog('success'.$obj);

            //转码完成 有转码

            if($EventType=='TranscodeComplete'){
                $this->relog('TranscodeComplete---'.$obj);

                $StreamInfos=json_encode($result["StreamInfos"]);
                $m3u8=$result["StreamInfos"][0]['FileUrl'];
                $mp4=$result["StreamInfos"][1]['FileUrl'];
                $res = Db::connect('')->name('plugin_aliyunvod')->where('video_id',$VideoId)->update(['stream_infos'=>$StreamInfos,'m3u8'=>$m3u8,'path'=>$mp4,'upload_status'=>4]);
            }

            //上传完成
            if($EventType=='FileUploadComplete'){
                $this->relog('FileUploadComplete---'.$obj);

                $m3u8=$result['FileUrl'];
                $path=$result['FileUrl'];
                $res = Db::connect('')->name('plugin_aliyunvod')->where('video_id',$VideoId)->update(['stream_infos'=>$obj,'m3u8'=>$m3u8,'path'=>$path,'upload_status'=>2]);
            }
        }
		  
    }
    /**
     * 上传本地mp4视频
     */
    public function upload(){
        
        $param = $this->request->param();

        $title = $param['title'];
        $cate = $this->request->param('category_id',0);
        $video = $_FILES['video'];


        if($video['name']!=''){
            $config = cmf_get_plugin_config('Aliyunvod');
            $accessKeyId = $config['AccessKeyId'];                    // 您的AccessKeyId
            $accessKeySecret =  $config['AccessKeySecret'];     // 您的AccessKeySecret
            $templateid = $config['TemplateGroupId'];
            $callbackurl = $config['CallbackURL'];
            $storageLoc = $config['StorageLocation'];

            $res = move_uploaded_file($video['tmp_name'],CMF_ROOT.'public/temp/'.$video['name']);

            $this->success('ok',$res);
            if($res){
               try {

                    //上传后返回视频id
                    $vid = $this->UploadLocalVideo($accessKeyId, $accessKeySecret, CMF_ROOT.'public/temp/'.$video['name'], $title,$templateid, $callbackurl,$storageLoc);
                    //删除本地
                
                    if($vid){
                        
                        unlink(CMF_ROOT.'public/temp/'.$video['name']);
                        
                        $data=[
                            'video_id'=>$vid,
                            'title'=>$title,
                            'category_id'=>$cate,
                            'create_time'=>time()
                        ];
                        $id = Db::connect('')->name('plugin_aliyunvod')->insertGetId($data);
                        if($id){
                            $this->success('上传完成',$id);
                        }
                        
                    }
                    
                } catch (Exception $e) {
                    var_dump($e);
                } 
            }
        }else{
            $this->error('请先上传视频！');
        }   
        
    }


    // 上传本地视频
   public function UploadLocalVideo($accessKeyId, $accessKeySecret, $filePath, $title ,$templateid, $callbackurl,$storageLoc)
    {
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($filePath, $title);
            $uploadVideoRequest->setCateId(1000174912);
            //$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
            //$uploadVideoRequest->setTags('test1,test2');
            $uploadVideoRequest->setStorageLocation($storageLoc);
            $uploadVideoRequest->setTemplateGroupId($templateid);
            $userData = array(
                "MessageCallback"=>array("CallbackURL"=>$callbackurl),
                "Extend"=>array("localId"=>"xxx", "test"=>"www")
            );
            $uploadVideoRequest->setUserData(json_encode($userData));
            

            $res = $uploader->uploadLocalVideo($uploadVideoRequest);
            

            return $res;
        } catch (Exception $e) {
            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }


    public function relog($word = '')
    {
        $word = is_array($word) ? var_export($word, 1) : $word;
        $fp = fopen( cmf_get_root().'temp/apilog.txt', 'a+');
        flock($fp, LOCK_EX);
        fwrite($fp, '执行日期：' . strftime('%Y%m%d%H%M%S', time()) . "\n" . $word . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}